package com.itheima.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.admin.exception.BusinessException;
import com.itheima.admin.interceptor.AdminHolder;
import com.itheima.admin.mapper.AdminMapper;
import com.itheima.server.ErrorResult;
import com.itheima.utils.Constants;
import com.itheima.utils.JwtUtils;
import com.itheima.domain.Admin;
import com.itheima.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public ResponseEntity login(Map<String,String> map){
        //获取请求的参数（username,password,verificationCode（验证码）,uuid）
        String username = map.get("username");
        String password =  map.get("password");

        String verificationCode =map.get("verificationCode");
        String uuid = map.get("uuid");

        //判断用户名或者密码是否为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            //用户名或者密码为空
            Map map1=new HashMap();
            map.put("message","用户名或者密码为空");
            return ResponseEntity.status(500).body(map1);
        }
        //判断验证码是否为空
        if (StringUtils.isEmpty(verificationCode)){
            //验证码为空
            throw new BusinessException(ErrorResult.verificationCodeError());
        }
        //从redis中获取验证码
        String key = Constants.CAP_CODE + uuid;
        String code = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)){
            //验证码错误
            throw new BusinessException(ErrorResult.verificationCode1Error());
        }
        //清除验证码缓存
        redisTemplate.delete(key);

        //根据用户名查询用户
        QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Admin admin=adminMapper.selectOne(queryWrapper);

        //判断用户是否存在，密码是否一致
        password= SecureUtil.md5(password);
        if (!admin.equals(password) || admin==null){
            throw new BusinessException(ErrorResult.userError());
        }

        //通过JWT生成token
        Map<String,Object> claims=new HashMap<String,Object>();
        claims.put("username",username);
        claims.put("id",admin.getId());
        String token= JwtUtils.getToken(claims);

        //构造返回值
        Map res=new HashMap();
        res.put("token",token);
        return ResponseEntity.ok(res);
    }

    //获取当前用户的用户资料
    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin selectById = adminMapper.selectById(userId);
        return AdminVo.init(selectById);
    }
}
